import { Request, toast, formatDate, fileUrl } from '../../utils/util.js'
import { ALIYUN_URL } from '../../utils/config.js'
let request = new Request()
let app = getApp()
Component({
  data: {
    isFirst : true,
    chatList : [],
    bargain : {}
  },
  methods : {
    load (e, last = 0) {
      let rows = e.detail.list
      let page = e.detail.page
      if (rows.length == 0 && page == 1) {
        this.setData({ chatList: null })
        return
      }
      if (rows.length > 0) {
        let chatList = this.data.chatList
        rows.forEach(v => {
          switch (v.chat_type) {
            case 1: v.url = '/pages/chat/index'; break;
            case 2:
            case 4:
            case 5: v.url = '/pages/goods/index'; break;
          }
          v.url += '?chatId=' + v.chat_id
          v.create_time = formatDate(v.create_time)
          v.picture = JSON.parse(v.picture)
          if(last == 0) {
            chatList.push(v)
          }else{
            chatList.unshift(v)
          }
        })
        this.setData({ chatList: chatList })
      }
    },

    praise(e) {
      let dataset = e.currentTarget.dataset
      let index = dataset.index
      let chatId = dataset.id
      let praise = dataset.praise
      request.get(praise == 0 ? 'chat/praise' : 'chat/unpraise', res => {
        if (res.success) {
          let update = {}
          update[`chatList[${index}].praise`] = praise == 0 ? 1 : 0
          this.setData(update)
        } else {
          toast(res.msg)
        }
      }, { id: chatId })
    },

    down(e) {
      let index = e.currentTarget.dataset.index
      let urls = this.data.chatList[index].picture
      urls.forEach(url => {
        wx.downloadFile({
          url: ALIYUN_URL + '/' + url,
          success: res => {
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: res => {
                console.log(res)
              },
              fail: res => {
                console.log(res)
              }
            })
            console.log(res)
          },
          fail: res => {
            console.log(res)
          }
        })
      })
    },


    toBargain(e) {
      let formId = e.detail.formId
      let index = e.target.dataset.index
      this.setData({ 'bargain.formId': formId, 'bargain.index': index })
      wx.navigateTo({
        url: '/pages/deliveryAddress/index?target=select'
      })
    },

    selectAddress(address) {
      setTimeout(() => {
        let bargain = this.data.bargain
        let chat = this.data.chatList[bargain.index]
        let index = bargain.index
        request.post('bargain/start', res => {
          if (res.success) {
            let bargainId = res.data.id
            let update = {}
            update[`chatList[${index}].bargain`] = 1
            update[`chatList[${index}].bargain_id`] = bargainId
            this.setData(update)
            wx.navigateTo({
              url: '/pages/bargain/index?id=' + bargainId
            })
          } else {
            toast(res.msg)
          }
        }, { id: chat.chat_id, address: address.id, formId: bargain.formId }).showLoading()
      }, 500)
    },

    goOnBargain(e) {
      let bargainId = e.currentTarget.dataset.id
      wx.navigateTo({
        url: '/pages/bargain/index?id=' + bargainId
      })
    },

    onLoad: function (options) {

    },

    onShareAppMessage: function (e) {
      if (e.from === 'button') {

        var queryStr = '?'

        let chat = this.data.chatList[e.target.dataset.index]
        let chatId = chat.chat_id
        let chatType = chat.chat_type
        let from = (chatType == 2 || chatType == 4 || chatType == 5) ? 'goods' : 'chat'

        queryStr += ('from=' + from)
        queryStr += ('&chatId=' + chatId)
        queryStr += ('&fromUserId=' + app.globalData.userInfo.user_id)

        if (chatType == 4) {
          let sharer = app.globalData.userInfo.user_id
          queryStr += ('&sharer=' + sharer)
          queryStr += '&dst=share'
        }

        var data = {
          path: '/pages/index/index?scene=' + encodeURIComponent(queryStr)
        }

        if(chatType == 1) {
          data.title = '分享一个有趣的故事给你'
        }else{
          data.title = chat.goods_name
        }

        if(chat.picture.length > 0) {
          data.imageUrl = fileUrl(chat.picture[0])
        }

        return data

      } else {

      }
    }
  },
  pageLifetimes: {
    show() { //获取位置
      if (this.data.isFirst) {
        this.setData({ isFirst : false})
      }else{
        var chatList = this.data.chatList
        if (chatList == null || chatList.length < 1) {
          let pagination = this.selectComponent('#pagination')
          pagination.initLoad()
        }else{
          var lastPk = chatList[0].chat_id
          var req = new Request()
          req.get('chat/dynamics', res => {
            if (res.success && res.data.list.length > 0) {
              this.load({ detail: { list: res.data.list, page: 1 } }, 1)
            }
          }, { lastPk: lastPk, last: 1 })
        }
        
      }
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selectedIndex: 1
        })
      }
    }
  }
})